import 'dart:math';

import 'package:chat_example/entity/chat_entity.dart';
import 'package:chat_example/measure_widget.dart';
import 'package:chat_example/model/chat_model.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:ok_image/ok_image.dart';

class SingleChatPage extends StatefulWidget {
  final String id;

  const SingleChatPage({
    Key key,
    this.id,
  }) : super(key: key);

  @override
  _SingleChatPageState createState() => _SingleChatPageState();
}

class _SingleChatPageState extends State<SingleChatPage> {
  String get id => widget.id;

  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('浪漫'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.trending_up),
            onPressed: _test,
          ),
        ],
      ),
      body: Container(
        child: ScopedModelDescendant<ChatModel>(
          builder: buildContainer,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        clipBehavior: Clip.antiAlias,
        child: Icon(Icons.add),
        onPressed: addMsg,
      ),
    );
  }

  Widget buildContainer(BuildContext context, Widget child, ChatModel model) {
    print("build container");
    var list = model.findWithEntity(id).reversed.toList();
    return ListView.builder(
      reverse: true,
      controller: _scrollController,
      itemCount: list.length,
      itemBuilder: (ctx, index) => buildItem(list[index]),
    );
  }

  Widget buildItem(ChatEntity entity) {
    bool isMine = entity.from == id;
    return Container(
      constraints: BoxConstraints(minHeight: 40.0),
      padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
      child: Row(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(40.0),
            child: OKImage(
              url: entity.headerUrl,
              width: 30.0,
              height: 30.0,
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 10.0),
              child: Text(
                entity.msg,
                // style: TextStyle(fontSize: 14.0),
              ),
            ),
          ),
        ],
        textDirection: isMine ? TextDirection.ltr : TextDirection.rtl,
      ),
    );
  }

  void addMsg() async {
    ChatEntity chatEntity = ChatEntity()
      ..from = id
      ..to = Random().nextInt(38293).toString()
      ..msg = Random().nextInt(38293).toString()
      ..headerUrl = "https://ws1.sinaimg.cn/large/844036b9ly1fy8ewlgqstj205k05k74a.jpg";

    var item = buildItem(chatEntity);
    var rect = await UIHelper.measureWidgetRect(
      context: context,
      widget: item,
      boxConstraints: BoxConstraints(minHeight: 40.0),
    );
    print(rect.width);
    print(rect.height);

    var model = ChatModel.of(context);
    model.addEntity(chatEntity);

    if (_scrollController.offset != 0) {
      _scrollController.jumpTo(
        _scrollController.offset + rect.height,
      );
    }
  }

  void _test() {
    print(_scrollController.offset);
  }
}
